import React, { Component } from 'react';
import {
  StyleSheet, Alert, Text, View, Image, TouchableOpacity,
  Platform
} from "react-native";
import { style } from '../../theme/style';
import { Common } from '../../component/common/Common';
import { GLOBAL } from '../../config/global';
import ToastUtil from '../../utils/toast';
import { CommonDialog } from '../../components/common/Dialog';
import * as Keychain from 'react-native-keychain';
import TouchID from 'react-native-touch-id';
import { STORAGE_CONSTANT } from '../../config/storage';
import StorageHelper from '../../utils/storageHelper';

const scale = GLOBAL.SCALE;
const touchIDImg = require('../../imgs/img-touchid.png');
export class SetUpPage extends Component {
  static navigationOptions = ({ navigation, navigationOptions }) => {
    return {
      headerTitle: '开通指纹登入',
      headerTintColor: style.color.white,
      headerLeft: <Text style={{ marginLeft: 18 * scale, color: '#fff' }} type="headLeft" onPress={() => { navigation.goBack() }} >返回</Text>,
      headerRight: null,
      headerStyle: {
        elevation: 0,
        backgroundColor: style.color.themeColor,
      },
      headerLeftStyle: {

      },
      headerTitleStyle: {
        flex: 1,
        textAlign: 'center'
      }
    }
  };

  constructor(props) {
    super(props)
    this.state = {
      isBind: false,
      modalVisible: false
    }
  };

  async componentWillMount () {
    if (GLOBAL.SUPPORT_BIOMETRY_TYPE) {
      this.setState({
        isBind: GLOBAL.BIND_BIOMETRY_AUTH
      })
    } else {
      // ToastUtil.showWarning('当前手机不支持识别，请返回首页')
    }
  }

  bindBiometry = async () => {
    TouchID.authenticate(`指纹识别${GLOBAL.BIND_BIOMETRY_AUTH ? '解绑' : '绑定'}`, {
      title: '通过识别键验证',
      imageColor: '#e00606',
      imageErrorColor: '#ff0000',
      sensorDescription: '请放入手指识别',
      sensorErrorDescription: '识别失败，请重试',
      unifiedErrors: true,
      fallbackLabel: '账号登录',
      cancelText: '取消',
      passcodeFallback: false,
    }).then(() => {
      GLOBAL.BIND_BIOMETRY_AUTH = !GLOBAL.BIND_BIOMETRY_AUTH
      StorageHelper.set(STORAGE_CONSTANT.BIND_BIOMETRY_AUTH, GLOBAL.BIND_BIOMETRY_AUTH);
      //判断app开启时默认类型
      if(GLOBAL.BIND_BIOMETRY_AUTH){
        GLOBAL.BIND_LOGIN_TYPE = 'BIOMETRY'
      }
      else if(GLOBAL.BIND_GESTURE_PASSWORD){
        GLOBAL.BIND_LOGIN_TYPE = 'GESTURE'
      }
      else{
        GLOBAL.BIND_LOGIN_TYPE = ''
      }
      StorageHelper.set(STORAGE_CONSTANT.BIND_LOGIN_TYPE, GLOBAL.BIND_LOGIN_TYPE);
      ToastUtil.showSuccess(`${GLOBAL.BIND_BIOMETRY_AUTH ? '开启' : '关闭'}成功`).then(() => {
        this.props.navigation.navigate('HomePage');
      })
    }).catch(error => {
      if (error.code === 'NOT_ENROLLED') {
        this.setState({
          modalVisible: true
        })
      } else if (error.code === 'UNKNOWN_ERROR') {
        ToastUtil.showWarning('出现未知错误,请再次验证');
      } else if (error.code !== 'USER_CANCELED' && error.code !== 'SYSTEM_CANCELED') {
        ToastUtil.showWarning('识别异常' + error.code);
      }
    });
  }

  _renderToastWrap = () => {
    return (
      <View>
        <View style={styles.itemRow}>
          <Text style={[styles.itemRowText]}>请去对应的手机中心去设置指纹验证</Text>
        </View>
      </View>
    )
  }

  render () {
    let { isBind, modalVisible } = this.state;
    return (
      <View style={styles.container}>
        {GLOBAL.SUPPORT_BIOMETRY_TYPE || GLOBAL.BIND_BIOMETRY_AUTH ? (
          <View>
            <View style={styles.itemBox}>
              <Image source={touchIDImg} style={styles.arrowIcon} />
            </View>
            <View style={styles.itemText}>
              <Text style={styles.itemTitle}>{isBind ? '您已绑定，可立即关闭' : '指纹/人脸登入 一触即达'}</Text>
            </View>
            <TouchableOpacity style={styles.itemCtn} onPress={() => { this.bindBiometry() }}>
              <Text style={styles.itemBtn}>
                {isBind ? '点击关闭' : '点击开启'}
              </Text>
            </TouchableOpacity>
            <CommonDialog modalVisible={modalVisible} title={'提示'} renderCustom={this._renderToastWrap} onClosePress={() => { this.setState({ modalVisible: false }) }} />
          </View>
        ) : <View style={styles.flexText}>
            <Text>请去对应手机设置中心开通指纹认证</Text>
          </View>
        }
      </View >
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  itemBox: {
    flexDirection: 'row',
    justifyContent: 'center',
    paddingTop: 56 * scale,
  },
  arrowIcon: {
    width: 80 * scale,
    height: 80 * scale,
    tintColor: 'red',
  },
  itemText: {
    flexDirection: 'row',
    justifyContent: 'center',
    paddingTop: 40 * scale,
  },
  itemTitle: {
    fontSize: 16 * scale,
    color: '#000',
  },
  itemCtn: {
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: 66 * scale,
    marginLeft: 20 * scale,
    marginRight: 20 * scale,
    paddingBottom: 20 * scale,
    paddingTop: 20 * scale,
    backgroundColor: '#0E7FFD',
    borderWidth: 1 * scale,
    borderStyle: 'solid',
    borderColor: '#0E7FFD',
    borderRadius: 5 * scale,
  },
  itemBtn: {
    fontSize: 16 * scale,
    color: '#fff',
  },
  itemRow: {
    flexDirection: 'row',
    justifyContent: 'center',
    paddingLeft: 30 * scale,
    paddingRight: 30 * scale,
  },
  itemRowText: {
    fontSize: 18 * scale,
  },
  flexText: {
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: 100 * scale,
    alignItems: 'center',
  },
})